package com.spring.mvc.http.test;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

import com.sun.crypto.provider.SunJCE;

public class SymmetryDemo {
	
	//提供对称密钥生成器功能，支持各种算法
	private KeyGenerator keygen;
	//负责保存对称密钥
	private SecretKey deskey;
	//负责完成加密解密功能
	private Cipher c;
	//保存加密后的结果
	private byte[] cipherByte;
	
	public SymmetryDemo() {
		Security.addProvider(new SunJCE());
		
		//实例化支持DES算法的密钥生成器（算法名称命名需按规定，否则抛出异常）
		try {
			//3DES DESede;AES AES;
			keygen=KeyGenerator.getInstance("DES");
			deskey=keygen.generateKey();
			c=Cipher.getInstance("DES");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 对给定字符串加密 
	 * @param str
	 * @return
	 */
	public byte[] createEncryptor(String str){
		try {
			//根据密钥，对Cipher对象进行初始化，ENCRYPT_MODE表示加密模式
			c.init(Cipher.ENCRYPT_MODE, deskey);
			byte[] bt=str.getBytes();
			cipherByte=c.doFinal(bt);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return cipherByte;
	}
	
	/**
	 * 解密
	 * @param buff
	 * @return
	 */
	public byte[] createDecryptor(byte[] buff){
		try {
			//根据密钥，对Cipher对象进行初始化，DECRYPT_MODE表示解密模式
			c.init(Cipher.DECRYPT_MODE, deskey);
			cipherByte=c.doFinal(buff);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return cipherByte;
	}
	
	public static void main(String[] args) {
		SymmetryDemo demo=new SymmetryDemo();
		String str="hello world! hello world!";
		byte[] bt=str.getBytes();
		for (int i = 0; i < bt.length; i++) {
			System.out.print(bt[i]+" ");
		}
		System.out.println();
		bt = demo.createEncryptor(str);
		for(int i=0;i<bt.length;i++){
			System.out.print(bt[i]+" ");
		}
		System.out.println();
		bt=demo.createDecryptor(bt);
		for(int i=0;i<bt.length;i++){
			System.out.print(bt[i]+" ");
		}
	}
}
